package com.gm.wj.controller;

import com.gm.wj.entity.*;
import com.gm.wj.result.Result;
import com.gm.wj.result.ResultFactory;
import com.gm.wj.service.*;
import com.gm.wj.util.MyTime;
import com.gm.wj.util.SysLoging;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.NonNull;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.HtmlUtils;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Login and register controller.
 *
 * @author Evan
 * @date 2019/4
 */
@Api(tags = "登录相关接口")
@Slf4j
@RestController
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    AdminRoleService roleService;
    @Autowired
    AdminUserRoleService adminUserRoleService;
    @Autowired
    SysStudentService sysStudentService;
    @Autowired
    SysTeacherService sysTeacherService;

    @PostMapping("/api/login")
    @ApiOperation("登录信息的接口")
    @SysLoging("登录")
    public Result login(@RequestBody User requestUser) {
        String username = requestUser.getUsername();
        username = HtmlUtils.htmlEscape(username);

        Subject subject = SecurityUtils.getSubject();
//        subject.getSession().setTimeout(10000);
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, requestUser.getPassword());
        usernamePasswordToken.setRememberMe(true);
        try {
            subject.login(usernamePasswordToken);
            User user = userService.findByUsername(username);
            if (!user.isEnabled()) {
                return ResultFactory.buildFailResult("该账号已被禁用");
            }
            // 查询得到所有的user数组  再从里面抽出Rid循环给rids
            List<Integer> rids = adminUserRoleService.listAllByUid(user.getId())
                    .stream().map(AdminUserRole::getRid).collect(Collectors.toList());
            if (rids.size() == 0) {
                return ResultFactory.buildFailResult("该账号的角色不存在，请联系管理员启用！");
            }
            AdminRole adminRole = roleService.findById(rids.get(0));
            if (!adminRole.isEnabled()) {
                return ResultFactory.buildFailResult("该账号的角色已被禁用，请联系管理员启用！");
            }
            return ResultFactory.buildSuccessResult("登录成功",username);
        } catch (IncorrectCredentialsException e) {
            return ResultFactory.buildFailResult("密码错误");
        } catch (UnknownAccountException e) {
            return ResultFactory.buildFailResult("账号不存在");
        }
    }

    // 注册
    @PostMapping("/api/register")
    @ApiOperation("注册信息的接口")
    @SysLoging("注册")
    public Result register(@RequestBody  @Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return ResultFactory.buildFailResult(bindingResult.getAllErrors().get(0).getDefaultMessage());
        }

        switch (userService.verifyCode(user)) {
            case 0:
                return ResultFactory.buildFailResult("邮箱格式错误！");
            case 2:
                return ResultFactory.buildFailResult("手机号格式错误！");
            default:
        }

        switch (user.getIdentity()) {
            case 0:
                log.info("进入管理员注册---"+user.getIdentity());
                user.setIdentity(0);// 管理员-0，学生-1，老师-2
                return getResult(user,0);
            case 1:
                log.info("进入学生注册---"+user.getIdentity());
                user.setIdentity(1);// 管理员-0，学生-1，老师-2
                return getResult(user,1);
            case 2:
                log.info("进入教师注册---"+user.getIdentity());
                user.setIdentity(2);// 管理员-0，学生-1，老师-2
                user.setIdentity(0);
                return getResult(user,2);
            default:
                return ResultFactory.buildFailResult("请选择用户身份");
        }
    }

    // 注册公共方法
    private Result getResult(@RequestBody User user,int flag) {
        int status = userService.register(user);
        AdminRole role;
        List<AdminRole> roles = new ArrayList<>();
        switch (status) {
            case 0:
                return ResultFactory.buildFailResult("用户名和密码不能为空");
            case 1:
                if (flag == 1){
                    role = roleService.findById(4); // 学生角色id为  4
                    roles.add(role);
                    user.setRoles(roles);
                    adminUserRoleService.saveRoleChanges(user.getId(), user.getRoles());
                    SysStudent sysStudent = new SysStudent();
                    sysStudent.setUsername(user.getUsername());
                    sysStudent.setStuName(user.getName());
                    sysStudent.setPhone(user.getPhone());
                    sysStudent.setEmail(user.getEmail());
                    sysStudent.setAddress("");
                    sysStudent.setStuNo("");
                    sysStudent.setCreateTime(MyTime.getStringDate());
                    sysStudentService.UseraddStu(sysStudent);
                }
                if (flag == 2) {
                    role = roleService.findById(5); // 老师角色id为  4
                    roles.add(role);
                    user.setRoles(roles);
                    adminUserRoleService.saveRoleChanges(user.getId(), user.getRoles());
                    SysTeacher sysTeacher = new SysTeacher();
                    sysTeacher.setUsername(user.getUsername());
                    sysTeacher.setTeaName(user.getName());
                    sysTeacher.setPhone(user.getPhone());
                    sysTeacher.setEmail(user.getEmail());
                    sysTeacher.setAddress("");
                    sysTeacher.setTeaNo("");
                    sysTeacher.setCreateTime(MyTime.getStringDate());
                    sysTeacherService.UseraddTea(sysTeacher);
                }
                return ResultFactory.buildSuccessResult("注册成功",null);
            case 2:
                return ResultFactory.buildFailResult("用户已存在");
        }
        return ResultFactory.buildFailResult("未知错误");
    }

    @GetMapping("/api/logout")
    @ApiOperation("退出的接口")
    @SysLoging("退出")
    public Result logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return ResultFactory.buildSuccessResult("成功登出",null);
    }

    @GetMapping("/api/authentication")
    @ApiOperation("身份认证的接口")
    @SysLoging("身份认证")
    public String authentication() {
        return "身份认证成功";
    }
}
